//
//  ModifyUserVC.swift
//  YunshuApp
//
//  Created by 周文杰 on 2017/5/10.
//  Copyright © 2017年 zwj. All rights reserved.
//

import UIKit
import BSImagePicker
import Kingfisher
import Photos

class ModifyUserVC: UIViewController {

    var keyboard:UIKeyboardViewController?
    let contentView = UIScrollView.init(frame: CGRect.init(x: 0, y: 0, width: Const.SCREEN_WIDTH, height: Const.SCREEN_HEIGHT))
    
    var headItem : XHInputItem?
    
    var nameItem : XHInputItem?
    var phoneItem : XHInputItem?
    var qqItem : XHInputItem?
    var wxItem : XHInputItem?
    var companyItem : XHInputItem?
    
    var positionItem : XHInputItem?
    var mailItem : XHInputItem?
    var birthdayItem : XHInputItem?
    var sexItem : XHInputItem?

    let datePicker = UIDatePicker.init(frame: CGRect.zero)
    
    let btn = UIButton.init(type: .roundedRect)

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "用户信息"
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "退出登录", style: .plain, target: self, action: #selector(ModifyUserVC.logout))
        
        self.view.backgroundColor = Const.WTM_WHITE_SMOKE
        self.contentView.backgroundColor = self.view.backgroundColor
        self.contentView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 64, right: 0)
        self.view.addSubview(self.contentView)
        
        headItem = XHInputItem("头像", onTap:self.onChooseHead)
        headItem?.showImage()
        headItem?.vseperator.isHidden = true
        if let url = URL(string:User.get.icon) {
            headItem?.thumbnail.kf.setImage(with: url)
        }
        self.contentView.addSubview(headItem!)
        
        nameItem = XHInputItem("姓名",placeHolder:"请输入姓名", onTap:nil)
        nameItem?.vseperator.isHidden = true
        nameItem?.setText(User.get.nickname)
        self.contentView.addSubview(nameItem!)

        phoneItem = XHInputItem("手机",placeHolder:"请输入手机号", onTap:nil)
        phoneItem?.isUserInteractionEnabled = false
        phoneItem?.vseperator.isHidden = true
        phoneItem?.setText(User.get.phone)
        self.contentView.addSubview(phoneItem!)
        
        qqItem = XHInputItem("QQ",placeHolder:"请输入QQ号", onTap:nil)
        qqItem?.vseperator.isHidden = true
        qqItem?.setText(User.get.qq)
        self.contentView.addSubview(qqItem!)
        
        wxItem = XHInputItem("微信",placeHolder:"请输入微信号", onTap:nil)
        wxItem?.vseperator.isHidden = true
        wxItem?.setText(User.get.wx)
        self.contentView.addSubview(wxItem!)
        
        companyItem = XHInputItem("公司",placeHolder:"请输入公司名称", onTap:nil)
        companyItem?.vseperator.isHidden = true
        companyItem?.setText(User.get.company)
        self.contentView.addSubview(companyItem!)
        
        positionItem = XHInputItem("职位", onTap:nil)
        positionItem?.vseperator.isHidden = true
        positionItem?.setText(User.get.position)
        self.contentView.addSubview(positionItem!)
        
        mailItem = XHInputItem("邮箱", onTap:nil)
        mailItem?.vseperator.isHidden = true
        mailItem?.setText(User.get.email)
        self.contentView.addSubview(mailItem!)
        
        birthdayItem = XHInputItem("生日", onTap:self.onTapBirthday)
        birthdayItem?.vseperator.isHidden = true
        birthdayItem?.setText(User.get.birthday)
        self.contentView.addSubview(birthdayItem!)
        
        sexItem = XHInputItem("性别", onTap:nil)
        sexItem?.vseperator.isHidden = true
        switch User.get.sex {
        case 0:
            sexItem?.setText("未设置")
        case 1:
            sexItem?.setText("男")
        case 2:
            sexItem?.setText("女")
        default: break
        }
        self.contentView.addSubview(sexItem!)
     
        let whiteView = UIView.init(frame: CGRect.init(x: 0, y: Const.SCREEN_HEIGHT - 64, width: Const.SCREEN_WIDTH, height: 64))
        whiteView.backgroundColor = UIColor.white
        
        btn.backgroundColor = Const.WTM_GREEN
        btn.setTitleColor(UIColor.white, for: .normal)
        btn.layer.cornerRadius = 5
        btn.addTarget(self, action: #selector(ModifyUserVC.submit), for: .touchUpInside)
        whiteView.addSubview(btn)
        btn.frame = CGRect.init(x: 10, y: 10, width: (Const.SCREEN_WIDTH - 20), height: 44)
        btn.setTitle("确定", for: .normal)

        self.view.addSubview(whiteView)
    }
    
    func onTapBirthday(_ item:XHInputItem) {
        datePicker.backgroundColor = Const.WTM_LIGHTGRAY
        datePicker.datePickerMode = .date
        datePicker.autoresizingMask = UIView.AutoresizingMask.flexibleWidth;
//        datePicker.dataSource = self;
//        datePicker.delegate = self;
        datePicker.frame = CGRect.init(x:0, y:Const.SCREEN_HEIGHT - 216, width:Const.SCREEN_WIDTH, height:216);
//        datePicker.showsSelectionIndicator = true
        self.view.addSubview(datePicker)
    }
    
    @objc func logout() {
        User.logout()
        self.navigationController?.popViewController(animated: true)
    }
    
    @objc func submit(){
        guard let model = self.collectInfo() else {
            return;
        }
        model.update(){
            isSuccess, resp in
            if isSuccess {
                let alert = UIAlertController(title: "提示", message:"恭喜你，修改个人信息成功！", preferredStyle: UIAlertController.Style.alert)
                alert.addAction(UIAlertAction(title: "我知道了", style: UIAlertAction.Style.cancel, handler: nil))
                self.navigationController?.present(alert, animated: true, completion: nil)
            }
        }
    }
    
    func collectInfo() ->User? {
        let requiredList = [nameItem,phoneItem,wxItem,companyItem]
        
        for item in requiredList {
            if item?.getText()?.count == 0 {
                self.navigationController?.view.makeToast((item?.hint)!)
                return nil
            }
        }
        let model = User.init()
        model.copyFrom(User.get)
        model.company = (companyItem?.getText())!
        model.phone = (phoneItem?.getText())!
        model.name = User.get.phone
        model.userId = User.get.userId
        model.icon = (headItem?.getText())!
        model.nickname = (nameItem?.getText())!
        model.qq = (qqItem?.getText())!
        model.wx = (wxItem?.getText())!
        
        model.position = (positionItem?.getText())!
        model.email = (mailItem?.getText())!
        model.birthday = (birthdayItem?.getText())!
        
        if (sexItem?.getText()?.contains("男"))! {
            model.sex = 1
        }else if (sexItem?.getText()?.contains("女"))! {
            model.sex = 2
        }else{
            model.sex = 0
        }
        return model;
    }
    
    
    func onChooseHead(_ params:XHInputItem) -> Void {
        let vc = ImagePickerController()
        vc.settings.list.cellsPerRow = { a, b in
            return 4
        }
        vc.settings.selection.max = 1
//        vc.settings.preview.takePhotos = true
        
        presentImagePicker(vc, animated: true, select: {(asset) in
            DispatchQueue.main.async {
                vc.dismiss(animated: true, completion: {
                    let image = self.getUIImage(asset: asset)
                    self.pickImage(image , onView:params)
                    
                })
            }
        }, deselect: nil, cancel: nil, finish: nil)
        
    }
    
    func getUIImage(asset: PHAsset) -> UIImage? {

        var img: UIImage?
        let manager = PHImageManager.default()
        let options = PHImageRequestOptions()
        options.version = .original
        options.isSynchronous = true
        manager.requestImageData(for: asset, options: options) { data, _, _, _ in

            if let data = data {
                img = UIImage(data: data)
            }
        }
        return img
    }
    
    func pickImage(_ image:UIImage?, onView:XHInputItem) {
        
        
        btn.backgroundColor = Const.WTM_GRAY
        btn.isEnabled = false
        
        _ = NetworkManager.Upload(NetworkManager.UPLOAD_IMG2, image: image, ownerVC: self, callback: { (isSucess, resp) in
            self.btn.backgroundColor = Const.WTM_GREEN
            self.btn.isEnabled = true
            if isSucess {
                let imgURL : String = resp.wtmDic["img"] as! String
                onView.thumbnail.image = image
                onView.valueField.text = imgURL
            }
        })
        
    }
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        var y:CGFloat = 10
        var i = 0
        for iView in contentView.subviews {
            if iView.isKind(of: XHInputItem.self) {
                let item : XHInputItem = iView as! XHInputItem
                item.setY(y)
                y += 46.0 - Const.ONE_PIXEL //压住线
                i += 1
                if ( i == 1 || i == 6 || i == 10) {
                    y += 10.0
                }
            }
        }
        
        self.contentView.contentSize = CGSize.init(width: Const.SCREEN_WIDTH, height: y + 46)
    }
}
